package com.zhuang.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zhuang.yygh.hosp.repository.DepartmentRepository;
import com.zhuang.yygh.hosp.service.DepartmentService;
import com.zhuang.yygh.model.hosp.Department;
import com.zhuang.yygh.vo.hosp.DepartmentQueryVo;
import com.zhuang.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 医院科室信息Service
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    //上传科室接口
    @Override
    public void save(Map<String, Object> paramMap) {
        //paramMap 转换department对象
        String paramMapString = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(paramMapString, Department.class);

        //根据医院编号 和 科室编号查询
        Department departmentExist = departmentRepository.
                getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        //判断
        if (departmentExist != null) {
            //更新操作
            //Mongodb会给每条数据自动生成_id的字段的值(即为实体类的id字段)，Mongodb不允许id字段出现重复
            //所以当能够根据条件查询到对象时，说明该对象的中数据存在于Mongodb集合中，所以当执行save()时执行的是修改操作
            //TODO: 可以修改数据，需要做一些优化，把传过来的数据赋给departmentExist对象
            departmentExist.setDepname(department.getDepname());
            departmentExist.setUpdateTime(new Date());
            departmentExist.setIsDeleted(0);
            departmentRepository.save(departmentExist);
        } else {//添加操作
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    //查询科室接口
    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        // 创建Pageable对象，设置当前页和每页记录数
        //0是第一页
        Pageable pageable = PageRequest.of(page - 1, limit);

        //把departmentQueryVo转换为department
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()//构建对象
                //改变默认字符串匹配方式：模糊查询
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                //改变默认大小写忽略方式：忽略大小写
                .withIgnoreCase(true);

        //条件对象，传入要查询的条件实体类以及匹配器对象
        Example<Department> example = Example.of(department, matcher);

        Page<Department> all = departmentRepository.findAll(example, pageable);
        return all;
    }

    //删除科室接口
    @Override
    public void remove(String hoscode, String depcode) {
        //根据医院编号 和 科室编号查询
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (department != null) {
            //调用方法删除
            departmentRepository.deleteById(department.getId());
        }
    }

    //根据医院编号，查询医院所有科室列表
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //创建list集合，用于最终数据封装
        List<DepartmentVo> result = new ArrayList<>();

        //根据医院编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        //条件对象
        Example example = Example.of(departmentQuery);
        //所有科室列表 departmentList
        List<Department> departmentList = departmentRepository.findAll(example);

        //根据大科室编号 bigcode 分组，获取每个大科室里面下级子科室
        //1.以stream流的方式将数据以bigcode作为分组依据，返回map集合，key就是每个bigcode，value就是属于该大科室下的所有数据的集合
        Map<String, List<Department>> deparmentMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        //2.遍历map集合 deparmentMap
        //2.1.获取当前Map集合的全部键的集合。
        Set<String> bigcodes = deparmentMap.keySet();
        //2.2.通过遍历键然后通过键取对应的值
        for (String bigcode : bigcodes) {
            //通过键取对应的值,通过大科室编号获取对应的数据集合
            List<Department> departments = deparmentMap.get(bigcode);
            //封装大科室
            DepartmentVo departmentVoBig = new DepartmentVo();
            departmentVoBig.setDepcode(bigcode);
            departmentVoBig.setDepname(departments.get(0).getBigname());
            //封装小科室
            List<DepartmentVo> childrenList = new ArrayList<>();
            for (Department department : departments) {
                DepartmentVo departmentVoSmall = new DepartmentVo();
                departmentVoSmall.setDepcode(department.getDepcode());
                departmentVoSmall.setDepname(department.getDepname());
                //封装到list集合
                childrenList.add(departmentVoSmall);
            }
            //把小科室list集合放到大科室children(下级节点)里面
            departmentVoBig.setChildren(childrenList);
            //放到最终的result集合里面
            result.add(departmentVoBig);
        }
        //返回
        return result;
    }

    //根据科室编号，和医院编号，查询科室名称
    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (department != null) {
            return department.getDepname();
        }
        return null;
    }

    //根据科室编号，和医院编号，查询科室对象
    @Override
    public Department getDepartment(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        return department;
    }
}
